package com.sen.common.exception;

import com.sen.common.lang.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.ShiroException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

//捕获异步异常,
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHander {

    //返回状态码，前端可以根据状态码，判断是否正常
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = RuntimeException.class)
    public Result hander(RuntimeException e){
        log.error("运行时异常：------------{}",e);
        return  Result.fail(e.getMessage());
    }

    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(value = ShiroException.class)
    public Result hander(ShiroException e){
        log.error("运行时异常：------------{}",e);
        return  Result.fail(401,e.getMessage(),null);
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result hander(MethodArgumentNotValidException e){
        log.error("实体校验异常：------------{}",e);
        //简要输出错误信息
        BindingResult bindingResult = e.getBindingResult();
        ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();

        return  Result.fail(401,objectError.getDefaultMessage(),null);
    }

    //断言异常
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = IllegalArgumentException.class)
    public Result hander(IllegalArgumentException e){
        log.error("Assert异常：------------{}",e);

        return  Result.fail(e.getMessage());
    }

}
